/**
 * 
 */
package com.cnhaimei.vod.logic;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import android.R.integer;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView.ScaleType;

import com.cnhaimei.com.HListView;
import com.cnhaimei.com.PageManager;
import com.cnhaimei.com.SearchTextView;
import com.cnhaimei.com.HListView.MyTouchListner;
import com.cnhaimei.com.PageManager.PageInfoListener;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.bean.Singer;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.net.dq.DQClose;
import com.cnhaimei.vod.net.dq.DQQuery;
import com.cnhaimei.vod.net.dq.DQQueryResult;
import com.cnhaimei.vod.net.dq.DQRead;
import com.cnhaimei.vod.net.dq.DQReadResult;
import com.cnhaimei.vod.net.dq.DQSinger;
import com.cnhaimei.vod.net.dq.SingerParser;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.ImageLoader;
import com.cnhaimei.vod.util.Util;
import com.cnhaimei.vod.util.Const.QueryType;

/**
 * 歌星列表
 * 
 * @author jin001.wu@gmail.com <br>
 * @date 2011-7-8
 * 
 */
public class SingerListActivity extends VODActivity implements
		PageInfoListener, MyTouchListner, TextWatcher {
	private static final int STATE_CLOSE = 0, STATE_OPENING = 1,
			STATE_OPENED = 2;
	private int mState = STATE_CLOSE;
	private static final int BASE_NUM = 10000000;

	private boolean mDCConnected = true;
	private static final String TAG = "SingerListActivity";
	private static final int PAGE_SIZE = 4;//14;
	// public static Singer selSinger;

	private Gallery bigLstView;
	private HListView smlLstView;
	private TextView curPageView;
	private TextView totalPageView;
	private View bigMapBt;
	private View lstBt;
	private View prePageView;
	private View nextPageView;

	private LayoutInflater mInflater;

	private AdapterExBig mBigAdapter;
	private AdapterEx mSmlAdapter;

	private PageManager pageManager;
	private HashMap<Long, Integer> pageReq = new HashMap<Long, Integer>();

	private SparseArray<ArrayList<Singer>> mPageCache = new SparseArray<ArrayList<Singer>>(
			200);
	private ArrayList<Singer> curSongList;
	private static long curSearchId = -1;
	private static DQQueryResult queryResult;
	private static DQQuery mQuery;
	private static int mQueryType;

	SoftReference<Drawable> BitmapCache;

	private boolean isNeting = false;
	private boolean isBigMap = false;
	private int totalCount;
	private boolean isClickedSinger;
	
	private String mTitle = "歌星点歌";
	private String mQueryString = DQQuery.QRY_STAR_ALL;
	private static String mLastQueryString;
	private String mQueryStringExtra = DQQuery.QRY_STAR_ALL;
	private String mQueryTable = DQQuery.TABLE_STAR;

	private View mHeadView;
	private SearchTextView mSearchView;
	private View mCancelView;
	private boolean mSearchViewFocused = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.v8_singer_list);

		String queryTable = getIntent().getStringExtra(Const.Key.QUERY_TABLE);
		if (queryTable != null && queryTable.length() > 0) {
			mQueryTable = queryTable;
		}
		
		String queryStr = getIntent().getStringExtra(Const.Key.QUERY_STRING);
		if (queryStr != null) {
			mQueryStringExtra = queryStr;
			mQueryString = mQueryStringExtra;
		}
		String title = getIntent().getStringExtra(Const.Key.TITLE_NAME);
		if (title != null) {
			mTitle = title;
		}
		else {
			mTitle = this.getResources().getString(R.string.star_title);
		}
		
		mQueryType = getIntent().getIntExtra(Const.Key.QUERY_TYPE, QueryType.COMMON);
		
		if (mLastQueryString != mQueryString) {
			mLastQueryString = mQueryString;
			
			DQManagerDisconnect();
		}	

		setTitle(mTitle);

		setClickable(R.id.big_map, R.id.list_bt, R.id.pre_page, R.id.next_page);//,	R.id.goback);
		
		mDCConnected = NetManager.G().isDQManagerAlive();
		if (queryResult == null || curSearchId == -1) {
			mState = STATE_CLOSE;
		} else {
			mState = STATE_OPENED;
		}
		
		pageManager = new PageManager();
		pageManager.setPageButtonView(findViewById(R.id.pre_page),
				findViewById(R.id.next_page), null, null);
		if (Util.DEMO) {
			//pageManager.setPageInfo(0, 4, false);
		}
		pageManager.setListener(this);
		mInflater = LayoutInflater.from(this);
		
		if (Util.DEMO) {
			curSongList = new ArrayList<Singer>(42);
			Bitmap bit = Util.loadStar("0119_CSY.jpg");// BitmapFactory.decodeResource(getResources(),
			// R.drawable.img0300);
			for (int i = 1; i < PAGE_SIZE; i++) {
				curSongList.add(Singer.createSinger("郑源" + (i * 100), bit));
			}
		}

		initView();


		if (mCancelView != null) {
			mCancelView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mSearchView != null) {
						mSearchView.clearFocus();
						mCancelView.setVisibility(View.GONE);
						mHeadView.setVisibility(View.VISIBLE);
						mSearchView.setText("");
					}					

					search(null);
				}
			});
		}
		if (mSearchView != null) {

			mSearchView.addTextChangedListener(this);//监听输入变化
			
			mSearchView.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					mSearchViewFocused = hasFocus;
				}
			});
			mSearchView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					if (mSearchViewFocused) {
//						mCancelView.setVisibility(View.VISIBLE);
//						mHeadView.setVisibility(View.GONE);
//					}
				}
			});
			mSearchView.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
					if(event.getAction() == KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){//修改回车键功能
						String search = mSearchView.getText().toString();
						search = search.trim();
						//if (search.length() > 0) 
						{
							
							// 先隐藏键盘
							((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
											SingerListActivity.this
											.getCurrentFocus()
											.getWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

							search(search);
						}
					}
				
					return false;					
				}
			});
		}
		

		setShowMode(false);

		XVod.G().registerListener(EventsManager.Event.QUERY_RESPONSE, this);
		XVod.G().registerListener(EventsManager.Event.QUERY_RECORDS, this);
		XVod.G().registerListener(EventsManager.Event.QUERY_QUERY, this);

		query();

		mSearchHandler.sendEmptyMessageDelayed(0, 1000);
	}

	private void initView() {
		curPageView = (TextView) findViewById(R.id.cur_page);
		totalPageView = (TextView) findViewById(R.id.total_page);
		bigMapBt = (View) findViewById(R.id.big_map);
		lstBt = (View) findViewById(R.id.list_bt);
		prePageView = findViewById(R.id.pre_page);
		nextPageView = findViewById(R.id.next_page);

		bigLstView = (Gallery) findViewById(R.id.gallery_list);
		smlLstView = (HListView) findViewById(R.id.small_list);
		smlLstView.setmMyTouchListner(this);
		// smlLstView.setNumColumns(7);
		if (mBigAdapter == null) {
			mBigAdapter = new AdapterExBig(true);
			bigLstView.setAdapter(mBigAdapter);
			bigLstView.setOnItemClickListener(mBigAdapter);
			bigLstView.setOnItemSelectedListener(mBigAdapter);
		}
		
		if (mSmlAdapter == null) {
			mSmlAdapter = new AdapterEx(false);
			smlLstView.setAdapter(mSmlAdapter);
			// smlLstView.setOnItemClickListener(mSmlAdapter);
			smlLstView.setOnItemSelectedListener(mSmlAdapter);
		}
		
		showBackBtn(true);

		
		mSearchView = (SearchTextView) findViewById(R.id.search_edit);
		mCancelView = findViewById(R.id.cancel_btn);
		mHeadView = findViewById(R.id.head);
		
		calculatePosition();
	}

	private int mImageViewHeight = 245;
	private int mImageViewWidth = 218;
	private int mPaddingTop = 0;
	private int mPaddingX = 0;
	private float mScaleX = 0;
	private float mScaleY = 0;
	private int mRealImgHeight = 188;
	private int mRealImgWidth = 177;

	private void calculatePosition() {
		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		float xdpi = dMetrics.widthPixels;//dMetrics.xdpi;
		float ydpi = dMetrics.heightPixels;//dMetrics.ydpi;
		float fScaleX = xdpi / 480;//xdpi / 240;
		float fScaleY = ydpi / 800;//ydpi / 240;
//		if (fScaleY == 1) {
//			mImageViewHeight = 225;
//			mRealImgHeight = 168;
//			//mRealImgWidth = 162;
//		}

		float fTopBottomScale = xdpi / 540;
		int nHeadHeight = (int)(98 * fTopBottomScale);//(int) (98 * fScaleY);
		int nFootHeight = (int)(116 * fTopBottomScale);//(int) (116 * fScaleY);		
		int nPanelHeight = dMetrics.heightPixels - nHeadHeight - nFootHeight - 68 - 75;
		mPaddingTop = (int)((nPanelHeight - (mImageViewHeight*2) * fScaleY) / 2);
		mPaddingX = (int)((dMetrics.widthPixels - (mImageViewWidth)*fScaleX*2)/4);
		mScaleX = fScaleX;
		mScaleY = fScaleY;
	}
	
	//调整中间6个板块的位置
	private void updatePosition(View rootView, View...views)
	{
		if (rootView != null) {
			if (mPaddingTop < 0) {
				mPaddingTop = 0;
			}
			rootView.setPadding(mPaddingX, mPaddingTop, mPaddingX, 0);
		}
		updateImageViewPos(mScaleX, mScaleY, mPaddingX, views);
	}

	protected void updateImageViewPos(float fScaleX, float fScaleY, int paddingX, View... views) {
		for (int i = 0; i < views.length; i++) {
			View v = views[i];
			if (v != null)
			{
				ViewGroup.LayoutParams lp = v.getLayoutParams();
				lp.height = (int)((int)mImageViewHeight * fScaleX);
				lp.width = (int) ((int)mImageViewWidth * fScaleX + paddingX*2);
				v.setLayoutParams(lp);
				
//				int paddingY = 0;
//				if (fScaleY == 1) {
//					View imageView = v.findViewById(R.id.image);
//					if (imageView != null) {
//						lp = imageView.getLayoutParams();
//						lp.height = (int)(mRealImgHeight* fScaleX);
//						lp.width = (int) (mRealImgWidth * fScaleX);
//						imageView.setLayoutParams(lp);
//					}
//					paddingY = 14;
//				}
				
				//((ImageView)v).setScaleType(ScaleType.FIT_XY);
				v.setPadding(paddingX, 0, paddingX, 0);
			}
		}
	}
	
	public void search(String search) {
		//清除原先的显示
		 if (queryResult != null) {
			 final DQQueryResult q = queryResult;
			 queryResult = null;
			 XVod.G().addRequest(new DQClose(q.getSnap()));
			 pageReq.clear();
			 mPageCache.clear();
		 }
		
		//搜索
		if (search != null && search.length() > 0) {
			int len = -1;
			try {
				len = Integer.parseInt(search);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if (len > 0 && len < 9) {
				mQueryString = DQQuery.getStarByLength(len);
			} else {
				mQueryString = DQQuery.createStarLikeName(search);
			}			
			mQueryString += " && " + mQueryStringExtra;
		}
		else {
			mQueryString = mQueryStringExtra;
		}
		if (mLastQueryString != mQueryString) {
			mLastQueryString = mQueryString;
			
			DQManagerDisconnect();

			if (queryResult == null || curSearchId == -1) {
				mState = STATE_CLOSE;
			} else {
				mState = STATE_OPENED;
			}

			pageManager.setCurrentIndex(0, false);
			
			query();
		}									
	}
	
	public static void DQManagerDisconnect() {
		curSearchId = -1;
		queryResult = null;
	}

	protected void onDQManagerDisconnect() {
		mDCConnected = false;
		curSearchId = -1;
		queryResult = null;
	}

	protected void onDQManagerReconnect() {
		mDCConnected = true;
		curSearchId = -1;
		queryResult = null;
		mState = STATE_CLOSE;
	}

	protected void query() {
		if (!mDCConnected) {
			return ;
		}
		if (mState == STATE_CLOSE) {
//		if (queryResult == null || curSearchId == -1) {
			// curSearchId = XVod.G().searchSinger();
			mQuery = new DQQuery(mQueryTable, mQueryString);
			mState = STATE_OPENING;
			curSearchId = XVod.G().addRequest(mQuery);
		} else {
			if (mState == STATE_OPENED && queryResult != null) {
				SingerParser sp = new SingerParser(queryResult);
				int total = queryResult.getRecordTotal();
				totalCount = total;
				int pageCount = (total > 0 ? total - 1 : 0) / PAGE_SIZE + 1;
				pageManager.setPageInfo(pageManager.getCurrentIndex(),
						pageCount, false);
//				loadData(sp, pageManager.getCurrentIndex());
				resetLstView();
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		isClickedSinger = false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (isFinishing()) {
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_RESPONSE,
					this);
			XVod
					.G()
					.unRegisterListener(EventsManager.Event.QUERY_RECORDS, this);
			 XVod.G().unRegisterListener(EventsManager.Event.QUERY_QUERY,this);
			pageReq.clear();
		}
	}

	@Override
	protected void onDestroy() {
		  if (queryResult != null) {
			  final DQQueryResult q = queryResult;
			  queryResult = null;
			  XVod.G().addRequest(new DQClose(q.getSnap()));			 
		  }
		// XVod.G().unRegisterListener(EventsManager.Event.QUERY_RESPONSE,
		// this);
		// XVod.G().unRegisterListener(EventsManager.Event.QUERY_RECORDS, this);
		// pageReq.clear();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.big_map:
			if (isBigMap) {
				break;
			}
			setShowMode(true);
			break;
		case R.id.list_bt:
			if (!isBigMap) {
				break;
			}
			setShowMode(false);
			break;
		case R.id.pre_page:
			break;
		case R.id.next_page:
			break;
		case R.id.goback:
			close();
			break;
		default:
			super.onClick(v); // need parent
			break;
		}
	}

	@Override
	public void onEvent(int event, Object obj, boolean isSuc) {
		switch (event) {
		case EventsManager.Event.QUERY_RESPONSE: {
			Log.e("onEvent", "isSuc" + isSuc);
			DQQueryResult res = (DQQueryResult) obj;
			if (isSuc) {
				if (res != null && curSearchId == res.getId()) {
					queryResult = (DQQueryResult) obj;
					if (queryResult.getRecordTotal() > 0) { // 服务器在重启后返回的是0记录，在此定义为无效查询
						SingerParser sp = new SingerParser(queryResult);
						mState = STATE_OPENED;
						int total = queryResult.getRecordTotal();
						totalCount = total;
						int pageCount = (total > 0 ? total - 1 : 0) / PAGE_SIZE
								+ 1;
						pageManager.setPageInfo(pageManager.getCurrentIndex(),
								pageCount, false);
//						loadData(sp, pageManager.getCurrentIndex());
						resetLstView();
					} else {
						XVod.G().addRequest(new DQClose(queryResult.getSnap()));
						mState = STATE_CLOSE;
						curSearchId = -1;
						queryResult = null;
						pageReq.clear();
						mPageCache.clear();
						pageManager.setPageInfo(0, 1, true);
						refreshPage();
					}
				}
			} else if (curSearchId == res.getId()) {
				mState = STATE_CLOSE;
				curSearchId = -1;
				queryResult = null;
				pageReq.clear();
				mPageCache.clear();
				pageManager.setPageInfo(0, 1, true);
				refreshPage();
			}
			else {
				mState = STATE_CLOSE;
				curSearchId = -1;
				queryResult = null;
				pageReq.clear();
				mPageCache.clear();
				pageManager.setPageInfo(0, 1, true);
				refreshPage();
			}
		}
			break;
		case EventsManager.Event.QUERY_RECORDS: {
			if (obj instanceof DQReadResult) {
				DQReadResult records = (DQReadResult) obj;
				if (isSuc && obj != null && queryResult != null) {
					long id = records.getId();
					Integer pg = pageReq.get(id);
					if (pg != null) {
						DQSinger singers = (DQSinger) obj;
						mPageCache.put(singers.getBegin(), singers.getList()); //
						// if (pageManager.getCurrentIndex() == pg) {
						// curSongList = singers.getList();
						refreshPage();
						// }
					}
				}
				if (records.getSnap() == 0) {
					mState = STATE_CLOSE;
				}
			}
		}
			break;
		case EventsManager.Event.QUERY_QUERY: {
			if (!isSuc) {
				mState = STATE_CLOSE;
			}
		} break;
		default:
			break;
		}
		super.onEvent(event, obj, isSuc);
	}

	public void onPageIndexChanged(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// final ArrayList<Singer> lst = mPageCache.get(currentPageIndex
		// * PAGE_SIZE);
		//
		// curSongList = lst;
		// refreshPage();
		// // }
		//
		// if (lst == null && queryResult != null) {
		// SingerParser sp = new SingerParser(queryResult);
		// loadData(sp, currentPageIndex);
		// }
		
		if (isBigMap) {
			int startPos = 0;
			if (totalCount > 0) {
				startPos = BASE_NUM / totalCount * totalCount;
			}
			startPos += currentPageIndex * PAGE_SIZE;
			bigLstView.setSelection(startPos, true);//currentPageIndex * PAGE_SIZE, true);
		} else {
			int count = pageManager.getTotalPage();
			int startPos = 0;
			if (count > 0) {
				startPos = BASE_NUM / count * count;
			}
			startPos += currentPageIndex;
			smlLstView.setSelection(startPos, true);//currentPageIndex, true);
		}

	}

	public void onPageIndexChangedError(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// TODO Auto-generated method stub

	}

	private void setShowMode(boolean isBigMap) {

		this.isBigMap = isBigMap;
		if (isBigMap) {
			bigLstView.setVisibility(View.VISIBLE);
			smlLstView.setVisibility(View.INVISIBLE);
			//lstBt.setBackgroundResource(R.drawable.list_button);
			//bigMapBt.setBackgroundResource(R.drawable.big_list_button_active);
			curPageView.setVisibility(View.INVISIBLE);
			totalPageView.setVisibility(View.INVISIBLE);
			prePageView.setVisibility(View.INVISIBLE);
			nextPageView.setVisibility(View.INVISIBLE);
		} else {
			bigLstView.setVisibility(View.INVISIBLE);
			smlLstView.setVisibility(View.VISIBLE);
			curPageView.setVisibility(View.VISIBLE);
			totalPageView.setVisibility(View.VISIBLE);
			prePageView.setVisibility(View.VISIBLE);
			nextPageView.setVisibility(View.VISIBLE);
			//lstBt.setBackgroundResource(R.drawable.list_buttonactive);
			//bigMapBt.setBackgroundResource(R.drawable.big_list_button);
		}

		if (isBigMap) {
			int startPos = 0;
			if (totalCount > 0) {
				startPos = BASE_NUM / totalCount * totalCount;
			}
			startPos += pageManager.getCurrentIndex() * PAGE_SIZE + 2;
			// bigLstView.setSelection(pageManager.getCurrentIndex() * PAGE_SIZE
			// + 2);
			bigLstView.setSelection(startPos);
		} else {
			int count = pageManager.getTotalPage();
			int startPos = 0;
			if (count > 0) {
				startPos = BASE_NUM / count * count;
			}
			startPos += pageManager.getCurrentIndex();
			smlLstView.setSelection(startPos);//pageManager.getCurrentIndex());
		}
		
		refreshPage();
	}
	
	// 重设
	private void resetLstView() {
		setShowMode(isBigMap);
	}

	private void refreshPage() {
		if (isBigMap) {
//			if (mBigAdapter == null) {
//				mBigAdapter = new AdapterExBig(true);
//				bigLstView.setAdapter(mBigAdapter);
//				bigLstView.setOnItemClickListener(mBigAdapter);
//				bigLstView.setOnItemSelectedListener(mBigAdapter);
//			}
//			// mBigAdapter.setList(curSongList);
			mBigAdapter.notifyDataSetChanged();
		} else {
//			if (mSmlAdapter == null) {
//				mSmlAdapter = new AdapterEx(false);
//				smlLstView.setAdapter(mSmlAdapter);
//				// smlLstView.setOnItemClickListener(mSmlAdapter);
//				smlLstView.setOnItemSelectedListener(mSmlAdapter);
//			}
//			// mSmlAdapter.setList(curSongList);
			mSmlAdapter.notifyDataSetChanged();
		}

		int total = pageManager.getTotalPage();
		//curPageView.setText(String.valueOf(pageManager.getCurrentIndex() + 1));
		//totalPageView.setText(String.valueOf(total));
		curPageView.setText(getString(R.string.cur_page, pageManager.getCurrentIndex() + 1));
		totalPageView.setText(getString(R.string.total_page, total));
	}

	public void loadData(SingerParser sp, int pageIndex) {
		if (pageReq.containsValue(pageIndex)) { // 已存在请求则不进行
			Log.e(TAG, "pageReq containsValue:" + pageIndex);
			return;
		}
		DQRead read = new DQRead(sp);
		read.setRequest(pageIndex * PAGE_SIZE, PAGE_SIZE);
		long id = XVod.G().addRequest(read);
		// long id = XVod.G().requestRecord(sp, pageIndex * PAGE_SIZE,
		// PAGE_SIZE);
		pageReq.put(id, pageIndex);
	}

	private void close() {
		finish();
	}

	private float oldX;
	private final float diff = 10;
	private int[] location = new int[2];
	private Rect rect = new Rect();

	public void onMyTouchListner(float x, float y, int e) {
		if (e == HListView.MyTouchListner.EVENT_DOWN) {
			oldX = x;
			return;
		}
		if (e == HListView.MyTouchListner.EVENT_UP) {
			if (Math.abs(oldX - x) < diff) {
				View root = smlLstView.getSelectedView();
				if (root == null || root.getTag() == null
						|| root.getVisibility() != View.VISIBLE) {
					return;
				}
				Log.e("SongListActivity:", "y:" + y);
				ViewHolder vh = (ViewHolder) root.getTag();
				// int index = (((int) (y - 63)) / vh.rows[0].getHeight())
				// % PAGE_SIZE;
				for (int i = 0; i < vh.rows.length; i++) {
					vh.rows[i].getGlobalVisibleRect(rect);
					if (rect.contains((int) x, (int) y)) {
						Object suTag = vh.rows[i].getTag();
						if (suTag instanceof SubViewHolder) {
							SubViewHolder subHodler = (SubViewHolder) suTag;
							String name = ((TextView) subHodler.name).getText()
									.toString();
							if (name != null && !"".equals(name.trim()) && !isClickedSinger) {
								isClickedSinger = true;
								StarSongsActivity.starActivity(
										SingerListActivity.this, name);
							}
						}
						return;
					}
				}
				// Object suTag = vh.rows[index].getTag();
				// if (suTag instanceof SubViewHolder) {
				// SubViewHolder subHodler = (SubViewHolder) suTag;
				// subHodler.bgImage.getLocationOnScreen(location);
				// subHodler.bgImage.getGlobalVisibleRect(rect);
				// if (rect.contains((int) x, (int) y)) {
				// String name = ((TextView) subHodler.name).getText()
				// .toString();
				// if (name != null && !"".equals(name.trim())) {
				// StarSongsActivity.starActivity(
				// SingerListActivity.this, name);
				// }
				// return;
				// }
				// subHodler.bgImage.setPressed(true);
			}
		}
	}

	public class AdapterExBig extends BaseAdapter implements
			OnItemClickListener, OnItemSelectedListener {
		private boolean isBigmap;

		public AdapterExBig(boolean isBigmap) {
			this.isBigmap = isBigmap;
		}

		// ArrayList<Singer> lst = new ArrayList<Singer>();
		//
		// public void setList(ArrayList<Singer> lst) {
		// this.lst = lst;
		// }

		public int getCount() {
			// return lst == null ? 0 : lst.size();
			if (totalCount <= PAGE_SIZE) {
				return totalCount;
			}
			return Integer.MAX_VALUE;
		}

		public Object getItem(int position) {
			return null;// lst.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolderBig holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.singer_big_item, null);
				holder = new ViewHolderBig();
				holder.initView(convertView);
			} else {
				holder = (ViewHolderBig) convertView.getTag();
			}

			holder.setValues(getItemByPos(position), position);

			return convertView;
		}

		private Singer getItemByPos(int position) {
			int totalPage = Math.max(1, pageManager.getTotalPage());
			// int page = (position / PAGE_SIZE) % totalPage;
			// int index = position % PAGE_SIZE;

			int totalSize = Math.max(1, totalCount);
			int realPos = position % totalSize;
			int page = (realPos / PAGE_SIZE) % totalPage;
			int index = realPos % PAGE_SIZE;

			Singer singer = readData(page, index);  
			return singer;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (isClickedSinger) {
				return;
			}
			
			Singer r = (Singer) getItemByPos(position);
			if (r != null) {
				isClickedSinger = true;
				StarSongsActivity.starActivity(SingerListActivity.this, r
						.getName());
			}
		}

		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			int total = Math.max(1, pageManager.getTotalPage());
			int page = 0;
			if (totalCount > 0) {
				page = (position % totalCount / PAGE_SIZE) % total;
			}

//			curPageView.setText(String.valueOf(page + 1));
//			totalPageView.setText(String.valueOf(total));
			curPageView.setText(getString(R.string.cur_page, page + 1));
			totalPageView.setText(getString(R.string.total_page, total));
			pageManager.setCurrentIndex(page, false);
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub

		}
	}

	public class AdapterEx extends BaseAdapter implements OnItemClickListener,
			OnClickListener, OnItemSelectedListener {
		private boolean isBigmap;

		public AdapterEx(boolean isBigmap) {
			this.isBigmap = isBigmap;
		}

		ArrayList<Singer> lst = new ArrayList<Singer>();

		public void setList(ArrayList<Singer> lst) {
			this.lst = lst;
		}

		public int getCount() {
			// return lst == null ? 0 : lst.size();
			if (isBigmap) {
				if (totalCount <= PAGE_SIZE) {
					return totalCount;
				}
			} else {
				int total = Math.max(0, pageManager.getTotalPage());
				if (total <= 1) {
					return total;
				}
			}
			return Integer.MAX_VALUE;
		}

		public Object getItem(int position) {
			return lst.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			// if (convertView == null) {
			// //
			// if (isBigmap) {
			// convertView = mInflater.inflate(R.layout.singer_big_item,
			// null);
			// holder = new ViewHolder();
			//
			// } else {
			// convertView = mInflater.inflate(R.layout.singer_sml_item,
			// null);
			// holder = new ViewHolderSml();
			// }
			// holder.initView(convertView);
			// convertView.setTag(holder);
			// } else {
			// holder = (ViewHolder) convertView.getTag();
			// }
			//
			// holder.setValues((Singer) getItem(position), position);
			//
			// return convertView;

			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.v8_singers_sml_page_items, null);
				convertView.setLayoutParams(new Gallery.LayoutParams(
						Gallery.LayoutParams.FILL_PARENT,
						Gallery.LayoutParams.FILL_PARENT));
				holder = new ViewHolder();
				holder.initView(convertView, this);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			int total = Math.max(1, pageManager.getTotalPage());
			int page = position % total;
			ArrayList<Singer> lst = readData(page);// mPageCache.get(PAGE_SIZE*position);
			holder.setValues(lst, page);

			return convertView;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (isClickedSinger) {
				return;
			}

			Singer r = (Singer) getItem(position);
			// selSinger = r;
			// if (isBigmap) {
			isClickedSinger = true;
			StarSongsActivity
					.starActivity(SingerListActivity.this, r.getName());
			// }
			// if (r != null && "108".equals(r.getNum())) {
			// startActivity(Const.Action.RoomMatched);
			// }

		}

		public void onClick(View v) {
			// TODO Auto-generated method stub
		}

		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			int total = Math.max(1, pageManager.getTotalPage());

//			curPageView.setText(String.valueOf(position % total + 1));
//			totalPageView.setText(String.valueOf(total));
			curPageView.setText(getString(R.string.cur_page, position % total + 1));
			totalPageView.setText(getString(R.string.total_page, total));
			pageManager.setCurrentIndex(position % total, false);
		}

		public void onNothingSelected(AdapterView<?> parent) {
		}
	}

	public ArrayList<Singer> readData(int pageIndex) {
//		if (mState == STATE_CLOSE) {
//			query();
//		}

		final ArrayList<Singer> lst = mPageCache.get(pageIndex * PAGE_SIZE);

		if (lst == null && mState == STATE_OPENED && queryResult != null) {
			SingerParser sp = new SingerParser(queryResult);
			loadData(sp, pageIndex);
		}

		return lst;
	}

	public Singer readData(int pageIndex, int index) {
		final ArrayList<Singer> lst = readData(pageIndex);
		if (lst != null && index < lst.size()) {
			return lst.get(index);
		}
		return null;
	}

	class ViewHolder {

		public View root;
		public View[] rows = new View[4];//[14];

		public void initView(View layout, OnClickListener lis) {
			root = layout;
			rows[0] = root.findViewById(R.id.item1);
			rows[1] = root.findViewById(R.id.item2);
			rows[2] = root.findViewById(R.id.item3);
			rows[3] = root.findViewById(R.id.item4);
			updatePosition(root, rows[0], rows[1], rows[2], rows[3]);
			/*
			rows[4] = root.findViewById(R.id.item5);
			rows[5] = root.findViewById(R.id.item6);
			rows[6] = root.findViewById(R.id.item7);
			rows[7] = root.findViewById(R.id.item8);
			rows[8] = root.findViewById(R.id.item9);
			rows[9] = root.findViewById(R.id.item10);
			rows[10] = root.findViewById(R.id.item11);
			rows[11] = root.findViewById(R.id.item12);
			rows[12] = root.findViewById(R.id.item13);
			rows[13] = root.findViewById(R.id.item14);
			*/
			for (int i = 0; i < rows.length; i++) {
				SubViewHolder subHolder = initSubView(rows[i], lis);
				rows[i].setTag(subHolder);
				// rows[i].setOnClickListener(lis);
			}
		}

		private SubViewHolder initSubView(View layout, OnClickListener lis) {
			SubViewHolder subHolder = new SubViewHolder();
			subHolder.image = (TextView) layout.findViewById(R.id.image);
			subHolder.name = (TextView) layout.findViewById(R.id.name);
			subHolder.bgImage = (TextView) layout.findViewById(R.id.bg_image);
			// subHolder.image.setOnClickListener(lis);
			return subHolder;
		}

		public void setValues(ArrayList<Singer> lst, int pos) {
			// subAdapterEx.setList(lst);
			// subAdapterEx.notifyDataSetChanged();
			int songSize = lst == null ? 0 : lst.size();
			for (int i = 0; i < rows.length; i++) {
				if (i < songSize) {
					rows[i].setVisibility(View.VISIBLE);
					setSubValues(lst.get(i), (SubViewHolder) rows[i].getTag(),
							pos * PAGE_SIZE + i);
				} else {
					rows[i].setVisibility(View.INVISIBLE);
					setSubValues(null, (SubViewHolder) rows[i].getTag(), pos
							* PAGE_SIZE + i);
				}
			}
		}

		private void setSubValues(Singer s, SubViewHolder holder, int pos) {
			holder.setValues(s, pos);
		}
	}

	class ViewHolderBig {

		public TextView name;
		public TextView image;

		public ViewHolderBig() {
		}

		public void initView(View layout) {
			layout.setLayoutParams(new Gallery.LayoutParams(256, 329));
			name = (TextView) layout.findViewById(R.id.name);
			image = (TextView) layout.findViewById(R.id.image);
		}

		public void setValues(Singer data, int pos) {
			if (data == null) {
				name.setText(null);
				image.setBackgroundDrawable(null);
				return;
			}
			name.setText(data.getName());
			// image.setBackgroundDrawable(new
			// BitmapDrawable(data.getBitmap()));
			Bitmap b = ImageLoader.G
					.getBitmap(mTaskListener, data.getImgName());
			if (b == null) {
				b = Util.DEFAULT_STAR;
			}
			image.setBackgroundDrawable(new BitmapDrawable(b));
		}

	}

	class SubViewHolder {
		public TextView name;
		public TextView image;
		public TextView bgImage;

		public void setValues(Singer data, int pos) {
			if (data == null) {
				image.setTag(data);
				name.setText(null);
				return;
			}
			name.setText(data.getName());
			Bitmap b = ImageLoader.G
					.getBitmap(mTaskListener, data.getImgName());
			if (b == null) {
				b = Util.DEFAULT_STAR;
			}
			image.setBackgroundDrawable(new BitmapDrawable(b));
		}
	}

	ImageLoader.ImageTaskListener mTaskListener = new ImageLoader.ImageTaskListener() {
		public void onLoadingFinished(Bitmap bitmap, String url) {
			if (bitmap != null) {
				if (isBigMap) {
					if (mBigAdapter != null) {
						mBigAdapter.notifyDataSetChanged();
					}
				} else if (mSmlAdapter != null) {
					mSmlAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}

	long currentTime = System.currentTimeMillis(); 
	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		mSearchHandler.removeMessages(0);
		
		String search = s.toString();

		if (search.trim().equals("")) {
			mSearchWord = null;
		}
		else {
			mSearchWord = search;
		}
  	  	mSearchHandler.sendEmptyMessageDelayed(0, 750);
		currentTime = System.currentTimeMillis(); 
	}

	String mSearchWord = "";
	String mLastSearchWord = "";
	
	//定义Handler对象
	private Handler mSearchHandler = new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      try {
	    	  mSearchHandler.removeMessages(0);
	    	  if (mSearchWord != mLastSearchWord) {
		    	  search(mSearchWord);
		    	  mLastSearchWord = mSearchWord;
	    	  }
	      }
	      catch(Exception e)
	      {
	    	  
	      }
	   }
	};
}
